import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

/*const {defineConfig} = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer:{
    port:9999
  }
})*/
// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueDevTools(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  // 防止 Vite 转换传统脚本
  build: {
    rollupOptions: {
      external: [
        /^\/assets\/vendors\/.*/,
        /^\/utils\/js\/.*/
      ]
    }
  },
  // 添加开发服务器配置
  server: {
    port: 3001,
    proxy: {
      '/api': {
        target: 'http://localhost:9001',
        changeOrigin: true,
        // 移除/api前缀
        rewrite: (path) => path.replace(/^\/api/, ''),
        secure: false,
        ws: true,
        timeout: 30000,
        onProxyReq(proxyReq, req, res) {
          // 记录详细的请求信息用于调试
          console.log(`代理请求: ${req.method} ${req.url} -> ${proxyReq.method} ${proxyReq.protocol}//${proxyReq.host}${proxyReq.path}`);
          console.log('请求头:', req.headers);
          console.log('代理请求路径:', proxyReq.path);
        },
        onProxyRes(proxyRes, req, res) {
          console.log(`代理响应: ${proxyRes.statusCode} ${req.url}`);
        },
        onError: (err, req, res) => {
          console.error('代理请求错误:', err);
          res.writeHead(500, {
            'Content-Type': 'text/plain',
          });
          res.end(`代理请求失败: ${err.message}`);
        }
      }
    }
  }
})
